<?php

/**
 * 公共控制器
 * ================================================
 * Copy 2010-2012
 * E-mail: chensgai2003@sina.com
 * ================================================
 * Author: yyserver32
 * header('Content-Type:text/html;charset=utf-8');
 * Date: 2017-4-7
 */

namespace common\Controller;
use Think\Controller;
class CommonController extends Controller
{
	
	public function generalThumb($src_path) {
		$flag = true;
		$info = pathinfo($src_path);  //文件信息
		$path = $info['dirname'];
		$max_file = $path.'/max_'.$info['basename'];
		$tmp_max_file = $path.'/tmp_max_'.$info['basename'];
		$min_file = $path.'/min_'.$info['basename'];
		$tmp_min_file = $path.'/tmp_min_'.$info['basename'];
		$extension = $info['extension'];  //扩展名
		if ($extension == 'jpeg') {
			$img_obj = new ThumbHandler();
			$img_obj->setSrcImg($src_path);
			$src_width = $img_obj->src_w;
			$src_height = $img_obj->src_h;
			$img_obj->setCutType(2);//指明为手工裁切
			if ($src_width >= $src_height) {
				//正常长方形,正方形
				if ($src_width > 375) {
					$const_scale = floor(($src_width / $src_height) * 10);  //宽高比例大于1.6
					if ($const_scale >= 16) {
						$max_scale = ceil((230/$src_height) * 100);
						$min_scale = ceil((85/$src_height) * 100);
					} else {
						$max_scale = ceil((375/$src_width) * 100);
						$min_scale = ceil((124/$src_width) * 100);
					}
				} else {
					$flag = false;
				}
			} else {
				//不正常的长方形,高大于宽
				if ($src_width > 375) {
					$max_scale = ceil((375/$src_width) * 100);  //为了防止压缩后图片小于生成的缩略图，这里取值稍大一点
					$min_scale = ceil((124/$src_width) * 100);
					
				} else {
					$flag = false;
				}
			}
			
			//大缩略图
			if ($flag) {
				$img_obj->setDstImg($tmp_max_file);
				$img_obj->createImg($max_scale);
				$img_obj->setSrcImg($tmp_max_file);
				$img_obj->setSrcCutPosition(0, 0);// 源图起点坐标
				$img_obj->setRectangleCut(375, 230);// 裁切尺寸
				$img_obj->setDstImg($max_file);
				$img_obj->createImg(375,230);
				$file_system1 = new FileSystem($tmp_max_file);
				$file_system1->delete_file($tmp_max_file);
				//小缩略图
				$img_obj->setSrcImg($src_path);
				$img_obj->setDstImg($tmp_min_file);
				$img_obj->createImg($min_scale);
				$img_obj->setSrcImg($tmp_min_file);
				$img_obj->setSrcCutPosition(0, 0);// 源图起点坐标
				$img_obj->setRectangleCut(124, 85);// 裁切尺寸
				$img_obj->setDstImg($min_file);
				$img_obj->createImg(124,85);
				$file_system2 = new FileSystem($tmp_min_file);
				$file_system2->delete_file($tmp_min_file);
			}
		} else if (($extension == 'jpg') || ($extension == 'png') || ($extension == 'gif') || ($extension == 'JPG')) {
			$image_info = getimagesize($src_path);  //图片信息
			$src_width = $image_info[0];
			$src_height = $image_info[1];
			if ($src_width >= $src_height) {
				//正常长方形  375*230  124*85
				if ($src_width > 400 && $src_height > 245) {
					if ((375/$src_width) > (230/$src_height)) {
						//高度有余,按宽度压缩
						
						/*大缩略图*/
						$image1 = new ZebraImage();
						$image1->source_path = $src_path;
						$image1->target_path = $tmp_max_file;
						$image1->resize(400, 0);  //原图宽为375，为了防止临时缩略图不够裁切，这里取值增大
						//裁剪
						$image2 = new ZebraImage();
						$image2->source_path = $tmp_max_file;
						$image2->target_path = $max_file;
						$image2->crop(0, 0, 375, 230);
						//删除临时文件
						$file_system1 = new FileSystem($tmp_max_file);
						$file_system1->delete_file($tmp_max_file);
						
						/*小缩略图*/
						$image3 = new ZebraImage();
						$image3->source_path = $src_path;
						$image3->target_path = $tmp_min_file;
						$image3->resize(140, 0);  //原图宽为124，为了防止临时缩略图不够裁切，这里取值增大
						//裁剪
						$image4 = new ZebraImage();
						$image4->source_path = $tmp_min_file;
						$image4->target_path = $min_file;
						$image4->crop(0, 0, 124, 85);
						//删除临时文件
						$file_system2 = new FileSystem($tmp_min_file);
						$file_system2->delete_file($tmp_min_file);
					} else {
						//高度不足,按高度压缩
						
						/*大缩略图*/
						$image1 = new ZebraImage();
						$image1->source_path = $src_path;
						$image1->target_path = $tmp_max_file;
						$image1->resize(0, 230);
						//裁剪
						$image2 = new ZebraImage();
						$image2->source_path = $tmp_max_file;
						$image2->target_path = $max_file;
						$image2->crop(0, 0, 375, 230);
						//删除临时文件
						$file_system1 = new FileSystem($tmp_max_file);
						$file_system1->delete_file($tmp_max_file);
						
						/*小缩略图*/
						$image3 = new ZebraImage();
						$image3->source_path = $src_path;
						$image3->target_path = $tmp_min_file;
						$image3->resize(0, 85);
						//裁剪
						$image4 = new ZebraImage();
						$image4->source_path = $tmp_min_file;
						$image4->target_path = $min_file;
						$image4->crop(0, 0, 124, 85);
						//删除临时文件
						$file_system2 = new FileSystem($tmp_min_file);
						$file_system2->delete_file($tmp_min_file);
					}
				} else {
					$flag = false;
					$max_file = '';
					$min_file = '';
				}
			} else {
				//不正常的长方形,高大于宽
				if ($src_width > 375) {
						/*大缩略图*/
						$image1 = new ZebraImage();
						$image1->source_path = $src_path;
						$image1->target_path = $tmp_max_file;
						$image1->resize(375, 0);
						//裁剪
						$image2 = new ZebraImage();
						$image2->source_path = $tmp_max_file;
						$image2->target_path = $max_file;
						$image2->crop(0, 0, 375, 230);
						//删除临时文件
						$file_system1 = new FileSystem($tmp_max_file);
						$file_system1->delete_file($tmp_max_file);
						
						/*小缩略图*/
						$image3 = new ZebraImage();
						$image3->source_path = $src_path;
						$image3->target_path = $tmp_min_file;
						$image3->resize(124, 0);
						//裁剪
						$image4 = new ZebraImage();
						$image4->source_path = $tmp_min_file;
						$image4->target_path = $min_file;
						$image4->crop(0, 0, 124, 85);
						//删除临时文件
						$file_system1 = new FileSystem($tmp_min_file);
						$file_system1->delete_file($tmp_min_file);
					
				} else {
					$flag = false;
					$max_file = '';
					$min_file = '';
				}
			}

		
		$return_data = array(
			'status' => $flag,
			'max_thumb' => $max_file,
			'min_thumb' => $min_file
		);
		return $return_data;
	}
        $flag = true;
        $info = pathinfo($src_path);
        $path = $info['dirname'];
        $max_file = $path.'/max_'.$info['basename'];
        $tmp_max_file = $path.'/tmp_max_'.$info['basename'];
        $min_file = $path.'/min_'.$info['basename'];
        $tmp_min_file = $path.'/tmp_min_'.$info['basename'];
        
        $img_obj = new ThumbHandler();
        $img_obj->setSrcImg($src_path);
        $src_width = $img_obj->src_w;
        $src_height = $img_obj->src_h;
        $img_obj->setCutType(2);//指明为手工裁切
        if ($src_width > $src_height) {
            //正常长方形
            if ($src_width > 375) {
                if ((375/$src_width) > (230/$src_height)) {
                    $max_scale = ceil((230/$src_height) * 100);
                    $min_scale = ceil((85/$src_height) * 100);
                } else {
                    $max_scale = ceil((375/$src_width) * 100);
                    $min_scale = ceil((124/$src_width) * 100);
                }
            } else {
                $flag = false;
            }
        } else {
            //不正常的长方形,高大于宽
            if ($src_width > 375) {
                $max_scale = ceil((375/$src_width) * 100);  //为了防止压缩后图片小于生成的缩略图，这里取值稍大一点
                $min_scale = ceil((124/$src_width) * 100);
                
            } else {
                $flag = false;
            }
        }
        
        //大缩略图
        if ($flag) {
            $img_obj->setDstImg($tmp_max_file);
            $img_obj->createImg($max_scale);
            $img_obj->setSrcImg($tmp_max_file);
            $img_obj->setSrcCutPosition(0, 0);// 源图起点坐标
            $img_obj->setRectangleCut(375, 230);// 裁切尺寸
            $img_obj->setDstImg($max_file);
            $img_obj->createImg(375,230);
            $file_system1 = new FileSystem($tmp_max_file);
            $file_system1->delete_file($tmp_max_file);
            //小缩略图
            $img_obj->setSrcImg($src_path);
            $img_obj->setDstImg($tmp_min_file);
            $img_obj->createImg($min_scale);
            $img_obj->setSrcImg($tmp_min_file);
            $img_obj->setSrcCutPosition(0, 0);// 源图起点坐标
            $img_obj->setRectangleCut(124, 85);// 裁切尺寸
            $img_obj->setDstImg($min_file);
            $img_obj->createImg(124,85);
            $file_system2 = new FileSystem($tmp_min_file);
            $file_system2->delete_file($tmp_min_file);
        }
        $return_data = array(
            'status' => $flag,
            'max_thumb' => $max_file,
            'min_thumb' => $min_file
        );
        return $return_data;
    }
    
    //上传文件
    /**
     * 自定义公共上传
     * @param  $upload_path  上传路径，注意是一个相对路么，在返回信息中是绝对路径
     * @return  array 返回信息数组
     */
    public function tp_upload($upload_path) {
		
        /*date_default_timezone_set('PRC'); //默认时区
		$str_date = date('Ymd', time());
		$save_path = './'.$upload_path.$str_date;
		if(!file_exists($save_path)){
			mkdir($save_path,0777,true);
		}*/
		
		
        $upload = new \Think\Upload();
        
        $upload->maxSize = '5242880';  //是指上传文件的大小，默认为-1,不限制上传文件大小bytes
        $upload->rootPath = $upload_path;       //上传保存到什么地方？路径建议大家已主文件平级目录或者平级目录的子目录来保存
        //$upload->saveName = time() . '_' . rand(1000, 9999);    //上传文件的文件名保存规则  time uniqid  com_create_guid  uniqid
        $upload->saveName = 'time';    //上传文件的文件名保存规则  time uniqid  com_create_guid  uniqid
        //$upload->autoCheck=false   ;  //是否自动检测附件
        //$upload->uploadReplace=true;     //如果存在同名文件是否进行覆盖
        $upload->allowExts=array('jpg','jpeg','png','gif');     //准许上传的文件后缀
        $upload->allowTypes=array('image/png','image/jpg','image/pjpeg','image/gif','image/jpeg');  //检测mime类型
        $upload->thumb=true;   //是否开启图片文件缩略
        //$upload->thumbMaxWidth='300,500';  //以字串格式来传，如果你希望有多个，那就在此处，用,分格，写上多个最大宽
        //$upload->thumbMaxHeight='200,400';	//最大高度
        //$upload->thumbPrefix='s_,m_';//缩略图文件前缀
        //$upload->thumbSuffix='_s,_m';  //文件后缀
        //$upload->thumbPath='' ;  // 如果留空直接上传至
        //$upload->thumbFile   在数据库当中也存一个文件名即可
        //$upload->thumbRemoveOrigin=1;  //如果生成缩略图，是否删除原图
        $upload->autoSub = true;   //是否使用子目录进行保存上传文件
        $upload->subName = array('date', 'Ymd');   //子目录创创方式默认为hash 也可以设为date
        //$upload->dateFormat = 'Ymd';  //子目录方式date的指定日期格式
        //$upload->hashLevle
        //upload()  如果上传成功，返回true,失败返回false
        $info = $upload->upload();
        if ($info) {
            //局部变量，你可以在此处，保存到一个超全局变量当中去进行返回
            //$info=$upload->upload();
            $result_info = array(
                'state' => 200,
                //'path' => substr($upload_path, 1),
                'path' => $upload_path,
                'info' => $info
            );
        } else {
            //是专门来获取上传的错误信息的
            //$this->error($upload->getErrorMsg());
            //echo $upload->getErrorMsg();
            $result_info = array(
                'state' => 300,
                //'path' => substr($upload_path, 1),
                'path' => $upload_path,
                'info' => $upload->getError()
            );
        }
        
        return $result_info;
    }

    /** 生成缩略图PicThumb方法
    *   $pic 图片路径
    *   $sta 返回图片尺寸， default 1024*768，max 375*230， min 124*85
    **/
    public function pictb($pic, $sta='default', $water = ''){
        $aa = getimagesize($pic);

        $size = $aa[0]/375*230;
        $ww = 'f';
        if ($size > $aa[1]) {
            $ww = 'w';
        }

        $size = $aa[0]/124*84;
        $hh = 'f';
        if ($size > $aa[1]) {
            $hh = 'w';
        }

        $size = $aa[0]/320*320;
        $oo = 'f';
        if ($size > $aa[1]) {
            $oo = 'w';
        }

        $arr = explode('/', $pic);

        for ($i=0; $i < count($arr); $i++) { 
            if ($i == count($arr)-1) {
                $dest1 .= 'max_thumb_'.$arr[$i];
                $dest2 .= 'min_thumb_'.$arr[$i];
                $dest3 .= 'default_thumb_'.$arr[$i];
                $dest4 .= 'logo_thumb_'.$arr[$i];
            }else{
                $dest1 .= $arr[$i].'/';
                $dest2 .= $arr[$i].'/';
                $dest3 .= $arr[$i].'/';
                $dest4 .= $arr[$i].'/';
            }
        }

// 按比例生成缩略图
        $mod = new PicThumb();
        switch ($sta) {
            case 'max':
            	$mess = $pic;
            	if ($aa[0] > 375 or $aa[1] > 230) {
	                $param = array(
	                    'type' => 'crop',
	                    'croppos' => 'TL',
	                    'width' => 375,
	                    'height' => 230,
	                    'style' => $ww
	                    );
	                
	                $mod->set_config($param);
	                $mod->create_thumb($pic, $dest1);
	                $mess = $dest1;
                }
                return $mess;
                break;
            case 'min':
                $param2 = array(
                    'type' => 'crop',
                    'croppos' => 'TL',
                    'width' => 124,
                    'height' => 85,
                    'style' => $hh
                );

                $mod->set_config($param2);
                $mod->create_thumb($pic, $dest2);
                return $dest2;
                break;
            case 'logo':
            	$mess = $pic;
            	if ($aa[0] > 320 or $aa[1] > 320) {
	                $param = array(
	                    'type' => 'crop',
	                    'croppos' => 'TL',
	                    'width' => 320,
	                    'height' => 320,
	                    'style' => $oo
	                    );
	                
	                $mod->set_config($param);
	                $mod->create_thumb($pic, $dest4);
	                $mess = $dest4;
                }
                return $mess;
                break;
            
            default:
                //如果图片太小直接使用原图
                $mess = $pic;
                if ($aa[0] > 800 or $aa[1] > 600) {
                	$param3 = array(
                        'type' => 'fit',
                        'croppos' => 'TL',
                    	'gravity' => 'Center',
                        'width' => 1024,
                        'height' => 768
                        );

                	if ($water === 'w') {
                		$param3['watermark'] = 'Public/Webapp/img/watermark.png';
                	}
                    
                    $mod->set_config($param3);
                    $mod->create_thumb($pic, $dest3);
                    $mess = $dest3;
                }
                return $mess;
                break;
        }

        return 'create thumb fail';
        
    }

/*
	*** $bigImgPath 背景图片地址
	*** $text  合成文字
	***  $font  文字字体
*/

	public function timage($bigImgPath,$text,$fontSize = 70,$left = 50,$top = 170, $imgname='small', $font = 'Public/yyuan.otf',$circleSize = 0){
	    $img = imagecreatefromstring(file_get_contents($bigImgPath));
	    $colors=imagecolorallocate($img,45,48,66);//字体颜色 RGB
	 
	    //$fontSize = 70;   //字体大小
	    //$circleSize = 0; //旋转角度
	    //$left = 50;      //左边距
	    //$top = 170;       //顶边距

	    imagefttext($img, $fontSize, $circleSize, $left, $top, $colors, $font, $text);
	    list($bgWidth, $bgHight, $bgType) = getimagesize($bigImgPath);
	    switch ($bgType) {
	        case 1: //gif
	            header('Content-Type:image/gif');
	            imagegif($img);
	            break;
	        case 2: //jpg
	            header('Content-Type:image/jpg');
	            imagejpeg($img);
	            break;
	        case 3: //png
	            imagesavealpha($img , true);//设置保存PNG时保留透明通道信息
	            $saveimg = 'Uploads/Marker/'.$imgname.'_'.time().'_'.rand(1000,9999).'.png';
	            imagepng($img, $saveimg);
	            break;
	        default:
	            break;
	    }
	    imagedestroy($img);
	    return $saveimg;
	}
	
    /**
     * php数据分页
     * @param array $data_list  要显示的数据列表
     * @param int $page         页码
     * @param int $page_size    每页显示条数
     * @param int $max_page     最大显示的页码
     * @param int $is_offset    页码显示是否使用偏移量1是0否，不使用偏移量则数据量大，页码增大，影响布局
     */
    public function loadMore($data_list, $page, $page_size = 20, $max_page = 10, $is_offset = 1) {
        $reponse = array(
            'status' => 200,
            'message' => '数据列表',
            'data' => array(),
            'page_info' => array()
        );
        $record_count = count($data_list);  //记录总数
		$page_size = $page_size ? $page_size : 20;  //每页记录条数
        $page = $page ? $page : 1;  //默认值
        $page_absolute = $page;
        $page_start = ($page_absolute - 1) * $page_size;  //起始页
        $page_count = ceil($record_count / $page_size);  //总页数
        //$item_num = $page * $page_size;  //每次取数据的偏移量，这里和js有所不同，js：从开始位置到结束位置，php:从开始位置取多少条
        $tmp_arr = array();  //用于存放返回数据
        if (($page * $page_size) > $record_count) {
            if (($page * $page_size - $page_size) < $record_count) {
                $tmp_arr = array_slice($data_list, $page_start);  //和js不同
                $reponse['data'] = $tmp_arr;
                //分页信息
                $reponse['page_info']['record_count'] = $record_count;
                $reponse['page_info']['page_size'] = $page_size;
                $reponse['page_info']['page'] = $page;
                $reponse['page_info']['page_count'] = $page_count;
                $reponse['page_info']['max_page'] = $max_page;
				$reponse['page_info']['is_offset'] = $is_offset;
            } else {
                $reponse['status'] = 300;
                $reponse['message'] = '没有搜索到相关数据！';
            }
        } else {
            $tmp_arr = array_slice($data_list, $page_start, $page_size);  //和js不同
            $reponse['data'] = $tmp_arr;
            //分页信息
            $reponse['page_info']['record_count'] = $record_count;
            $reponse['page_info']['page_size'] = $page_size;
            $reponse['page_info']['page'] = $page;
            $reponse['page_info']['page_count'] = $page_count;
            $reponse['page_info']['max_page'] = $max_page;
			$reponse['page_info']['is_offset'] = $is_offset;
        }
        return $reponse;
    }


}





